<?php
require(PATH2LIB.'function.xml_encode.php');

require(PATH2LIB.'class.exception.php');

require(PATH2LIB.'class.uri.php');
require(PATH2LIB.'class.map.php');

require(PATH2LIB.'class.dataobject.php');

require(PATH2LIB.'class.dbfactory.php');

require(PATH2RESPONSES.'class.responsedata.php');
require(PATH2RESPONSES.'class.response.php');
require(PATH2RESPONSES.'class.responsehtm.php');
require(PATH2RESPONSES.'class.responsexsl.php');
require(PATH2RESPONSES.'class.responsexml.php');
require(PATH2RESPONSES.'class.responsejson.php');

require(PATH2LIB.'class.xhtmlscrubber.php');
require(PATH2LIB.'class.xhtmlvalidator.php');

class Elementary
{
	const VERSION = "0.3a1";
	private static $instance = null;
	
	
	private $response = array();
	
	private $current_uri = null;
	
	public function __construct($response) {
		$this->response = $response;
		
		$this->current_uri = Map::getInstance()->getURI((string)URI::getInstance());
		
		DataObject::$system['uri'] = (array)URI::getInstance();
		
		if (!$this->current_uri) {
			return false; // error 404, uri not found
		}
		
		$this->executeParents();
		
		$this->loadResponses($this->current_uri);
	}
	
	public static function getInstance($response = null) {
		if (self::$instance == null && $response != null) {
			self::$instance = new Elementary($response);
		}
		
		return self::$instance;
	}
	
	private function loadResponses() {
		$map = Map::getInstance();
		$uri = URI::getInstance();
		
		foreach ($this->response as $k => $v) {
			if ($uri->getResponse() == $k) {
				$class_name = 'Response'.$v;
				
				$response = new $class_name($map[$this->current_uri]['name']);
				header($response->header);
				echo $response;
			}
		}
	}
	
	private function executeParents() {
		$parents = array();
		
		$map = Map::getInstance();
		$uri = URI::getInstance();
		
		$parent = $this->current_uri;
		
		while ($parent != '') {
			$parents[] = $parent;
			$parent = $map[$parent]['parent'];
		}
		
		$parents = array_reverse($parents);
		$variables = array();
		
		for ($i=1, $real=explode('/', (string)$uri), $pcre=explode('/', $this->current_uri), $c=count($real), $current=''; $i<$c; $i++) {
			if (preg_match('@^'.$pcre[$i].'$@', $real[$i], $vars)) {
				
				$current .= '/'.$pcre[$i];
				
				for ($j=1, $vc=count($vars); $j<$vc; $j++) {
					$variables[$map[$current]['vars'][($j-1)]] = $vars[$j];
				}
			}
		}
		
		DataObject::$system['vars'] = $variables;
		
		foreach ($parents as $parent) {
			$filename = PATH2LOGIC.$map[$parent]['name'].'.php';
			if (file_exists($filename)) {
				require_once($filename);
				if (method_exists($map[$parent]['name'], 'pre')) {
					call_user_func(array($map[$parent]['name'], 'pre'));
				}
			}
		}
	}
}
?>